﻿using System;
using System.Html;

namespace JenkinsView
{
    public class ServerModel : Model
    {
        private int _selectedSvrIdx = -1;
        public int SelectedServerIndex
        {
            get { return _selectedSvrIdx; }
            set { _selectedSvrIdx = value; }
        }

        private JenkinsServer[] _svrs = new JenkinsServer[] { };
        public JenkinsServer[] ListServers()
        {
            return _svrs;
        }

        public JenkinsServer ListCurrentServer()
        {
            return _svrs[_selectedSvrIdx];
        }

        public void LoadServersFromStorage()
        {
            string val = Storage.LoadData();
            Console.Log("load:" + val);
            if (val == null)
                return;
            _svrs = JSON.Parse<JenkinsServer[]>(val);
            this.Notify(DomainModel.SVR_LIST_CHANGE, null);
        }

        public void RequestAppendServer()
        {
            DomainModel.Model.NotifyAll(DomainModel.EDIT_SVR, null);
        }

        public string AppendServer(JenkinsServer svr)
        {
            foreach (var s in _svrs)
            {
                if (s.SvrName == svr.SvrName)//Note: Duplicate server name.
                {
                    return "Server name exist.";
                }
            }
            if (svr.SvrName == null || svr.SvrName.Length == 0)
                return "Name is mandatory.";
            if (svr.Url == null || svr.Url.Length == 0)
                return "Url is mandatory.";
            //Console.Log("-----------" + svr.Url.IndexOf("http://"));
            //Console.Log("-----------" + svr.Url.IndexOf("https://"));
            if (svr.Url.IndexOf("http://") != 0 && svr.Url.IndexOf("https://") != 0)
                svr.Url = "http://" + svr.Url;
            if (svr.Url.CharAt(svr.Url.Length - 1) != '/')
                svr.Url = svr.Url + '/';

            _svrs.Push(svr);

            Storage.SaveData(JSON.Stringify(_svrs));

            DomainModel.Model.NotifyAll(DomainModel.SVR_LIST_CHANGE, null);
            return null;
        }

        private int _requestRemoveIdx;
        public void RequestRemoveServer(int idx)
        {
            _requestRemoveIdx = idx;
            DomainModel.Model.NotifyAll(DomainModel.CONFIRM_DEL, null);
        }

        public void RemoveServer()
        {
            _svrs.Splice(_requestRemoveIdx, 1);

            Storage.SaveData(JSON.Stringify(_svrs));

            DomainModel.Model.NotifyAll(DomainModel.SVR_LIST_CHANGE, null);
        }
    }
}
